﻿using Server.Framework.Util;
using System;

namespace Server.Framework.Message
{
    /// <summary>
    /// Author: Leil
    /// Description: 消息解码
    /// CreateTime: 2020/5/11 17:02:49
    /// </summary>
    class MessageDecoder
    {
        /// <summary>
        /// 消息反序列化
        /// 消息序列化规则：
        /// 4byte==>传输类型
        /// 4byte==>客户端版本号
        /// 4byte==>消息号
        /// 4byte==>消息体长度
        /// 消息体
        /// </summary>
        /// <returns>消息体</returns>
        public static RequestBaseMessage Decode(byte[] buffer, int offset)
        {
            // 消息类型先不做处理
            int msgType = BufferUtil.GetInt(buffer, offset);
            float versionId = BufferUtil.GetFloat(buffer, offset + 4);
            int msgId = BufferUtil.GetInt(buffer, offset + 8);
            int bodyLength = BufferUtil.GetInt(buffer, offset + 12);

            if (buffer.Length - offset < bodyLength + 16)
            {
                return null;
            }

            Type type = MessageTypeManager.GetType(msgId);
            if (type == null)
            {
                return null;
            }
            object instance = Activator.CreateInstance(type);
            if (!(instance is RequestBaseMessage message))
            {
                return null;
            }
            message.MsgId = msgId;
            message.Version = versionId;

            byte[] body = new byte[bodyLength];
            Array.Copy(buffer, offset + 16, body, 0, bodyLength);
            message.Deserialize(body);
            return message;
        }


        /// <summary>
        /// 消息序列化
        /// </summary>
        /// <param name="version">版本号</param>
        /// <param name="msgId">消息号</param>
        /// <param name="body">消息体</param>
        /// <returns>序列化后的buffer</returns>
        public static byte[] Encode(float version, int msgId, byte[] body)
        {
            int msgType = 1; // 消息类型暂定为1，不做处理
            int bodyLength = body.Length;
            byte[] buffer = new byte[16 + bodyLength];
            Array.Copy(BitConverter.GetBytes(msgType), 0, buffer, 0, 4);
            Array.Copy(BitConverter.GetBytes(version), 0, buffer, 4, 4);
            Array.Copy(BitConverter.GetBytes(msgId), 0, buffer, 8, 4);
            Array.Copy(BitConverter.GetBytes(bodyLength), 0, buffer, 12, 4);
            Array.Copy(body, 0, buffer, 16, bodyLength);
            return buffer;
        }


    }
}
